package com.customization.api.irecordset.cmd;


import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.SplitPageParaBean;
import weaver.general.SplitPageUtil;
import weaver.general.Util;
import weaver.hrm.User;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IRecoderSetCmd   extends AbstractCommonCommand<Map<String,Object>> {

    public IRecoderSetCmd(User user, Map<String,Object> params) {
        this.user = user;
        this.params = params;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {





        Map<String, Object> apidatas = new HashMap<String, Object>();
        apidatas.put("v", "2020071601");
        apidatas.put("status", 0);

        int userid=user.getUID();
        int seclevel= Util.getIntValue(user.getSeclevel(),0);
        int pageNo = Util.getIntValue( Util.null2String(params.get("pageNo")),1);
        String apikey =  Util.null2String(params.get("apikey"));
        String debug =  Util.null2String(params.get("debug"));

        RecordSet rs2 = new RecordSet();
        RecordSet rs1 = new RecordSet();
        apidatas.put("apikey", apikey);


        boolean operatelevel=false;
        boolean operaterole=false;
        rs1.execute("select * from uf_sqlset where apikey='"+apikey+"'");
        if(rs1.first()){
            String  roleid=  Util.null2String(rs1.getString("fwqxjs"));//角色ID;
            if("".equals(roleid))roleid="-1";
            int  seclevelstart=  Util.getIntValue(Util.null2String(rs1.getString("fwqxaqjb")),-1);//安全级别开始;
            int  seclevelend=  Util.getIntValue(Util.null2String(rs1.getString("fwqxaqjbjs")),-1);//安全级别结束;


            //登录人的安全级别在设置的范围内 或者在设置的角色内
            if((seclevelstart==-1&seclevelend==-1)||(seclevelstart<=seclevel&&seclevel<=seclevelend)){//安全级别不受限
                operatelevel=true;
            }

            rs2.execute("select id from hrmrolemembers where roleid in （"+roleid+"） and resourceid ='"+user.getUID()+"'");
            if("-1".equals(roleid)||rs2.next()){//角色有权限
                operaterole=true;
            }
            String  sql= rs1.getString("sqlfrom");
            if(debug.equals("1")){
                apidatas.put("原始sql", sql);
                apidatas.put("可查看角色", roleid+":"+operaterole);
                apidatas.put("可查看安全级别", ""+seclevelstart+" - "+seclevelend+":"+operatelevel);
            }

            if(operaterole||operatelevel){

                sql=getStringNoBlank(sql);
                String primaryKey = rs1.getString("PRIMARYKEY");
                String sqlOrderBy = Util.null2String(rs1.getString("sqlOrderBy"));
                int sortWay = Util.getIntValue( Util.null2String(rs1.getString("sortWay")),0);
                int pageSize = rs1.getInt("PAGESIZE");
                if(pageSize==0) pageSize=99999;

                while (sql.indexOf("{")>0){
                    String param=sql.substring(sql.indexOf("{"),sql.indexOf("}")+1);
                    String  p=param.replace("{?","").replace("}","");

                    if(p.equals("userid")){
                        sql=sql.replace(param,""+userid);
                    }else{
                        sql=sql.replace(param,Util.null2String(params.get(p)));
                    }

                }

                sql= sql.replace("?"," ");
                sql= sql.replace("？"," ");
                if(debug.equals("1")){
                    apidatas.put("最终执行sql", sql);
                    apidatas.put("primaryKey", primaryKey);
                }
                Console.log("apikey:"+apikey+";userid:"+userid+";exec:"+sql);

                /*分页查询代码，标准代码*/
                SplitPageParaBean spp = new SplitPageParaBean();
                spp.setSqlFrom("("+sql+") t1");
                spp.setPrimaryKey(primaryKey);
                spp.setBackFields("*");
                if(!sqlOrderBy.equals("")) {
                    spp.setSqlOrderBy(sqlOrderBy);    //排序字段 t1.
                }
                if(sortWay>0) {
                    spp.setSortWay(sortWay);    //0 升序   1 降序
                }

                SplitPageUtil spu = new SplitPageUtil();
                spu.setSpp(spp);
                RecordSet rs = spu.getCurrentPageRs(pageNo,pageSize);

                /*将查询结果按照 字段名作为key，字段值作为value 动态封装成json，标准代码*/
                int totalSize = spu.getRecordCount();
                JSONArray datas = new JSONArray();
                String[] columnNames = rs.getColumnName();
                while(rs.next()){
                    JSONObject jsonObj = new JSONObject();
                    for(String columnName : columnNames){
                        jsonObj.put(columnName.toLowerCase(), Util.formatMultiLang(rs.getString(columnName)));
                    }
                    datas.add(jsonObj);
                }

                apidatas.put("datas", JSONArray.fromObject(datas));
                apidatas.put("pageSize", pageSize);
                apidatas.put("pageNo", pageNo);
                apidatas.put("totalSize", totalSize);
                apidatas.put("currentPageSize", datas.size());

                if(datas.size()==0){
                    apidatas.put("status", -2);
                    apidatas.put("statusinfo", "没有返回值");
                }
            }else{
                apidatas.put("status", -3);
                apidatas.put("statusinfo", "无权限访问；");
            }

        }else{
            apidatas.put("status", -1);
            apidatas.put("statusinfo", "apikey不存在");
        }

        if(debug.equals("1")){
            JSONObject paramObj = new JSONObject();
            paramObj.put("入参:pageNo", "第几页，默认值1");
            paramObj.put("入参:apikey", "接口标识");
            paramObj.put("出参:datas", "返回的结果集");
            paramObj.put("出参:currentPageSize", "当前返回的结果集数量");
            paramObj.put("出参:status", "0:正常返回数据；-3:无权限访问；-2:未查询到数据；-1:apikey不存在；");
            apidatas.put("desc", paramObj);
        }


        return apidatas;
    }

    public static String getStringNoBlank(String str) {
        if(str!=null && !"".equals(str)) {
            Pattern p = Pattern.compile("\t|\r|\n");
            Matcher m = p.matcher(str);
            String strNoBlank = m.replaceAll(" ");
            p = Pattern.compile("\\&[a-zA-Z]{1,10};");
            m = p.matcher(strNoBlank);
            strNoBlank = m.replaceAll(" ");
            strNoBlank= strNoBlank.replace("  "," ");
            return strNoBlank;
        }else {
            return str;
        }
    }
}
